# ----------------------------------------------------------
#   |  author  : wenqvip                  |     \|/      |
#   |  email   : wenqvip@gmail.com        |    --+--     |
#   |  version : 0.2.1                    |     /|\      |
# ----------------------------------------------------------

OUT=a.out

CC=gcc
CXX=g++
LD=g++

SRCS=$(wildcard *.cpp)
SRCS+=$(wildcard obj_impgl/*.cpp)
SRCS+=$(wildcard obj_interface/*.cpp)
SRCS+=$(wildcard *.c)
REJECT_SRCS=

# must add this so that make can find cpp in these sub dirs
vpath %.cpp ./obj_impgl
vpath %.cpp ./obj_interface

DEFINES=
INCLUDES=
ARG_m32=-m32
ARG_v=#-v
ARG_g=-g
ARG_O=#O2

PRE_MAKE_DIRS=

CFLAGS=$(ARG_g) $(ARG_O) $(ARG_v) $(ARG_m32) $(DEFINES)
CXXFLAGS=$(ARG_g) $(ARG_O) $(ARG_v) $(ARG_m32) $(DEFINES)
LDFLAGS=$(ARG_v) -lGL -lfreeglut

ALL_OBJS=$(addsuffix .o,$(basename $(SRCS)))
REJECT_OBJS=$(addsuffix .o,$(basename $(REJECT_SRCS)))
OBJS=$(notdir $(filter-out $(REJECT_OBJS),$(ALL_OBJS)))
DIR_OBJS=objs

DIR_DEPS=.deps
DEPS=$(patsubst %.o,%.d,$(OBJS))

PWD=$(shell pwd)

ifdef PRE_MAKE_DIRS
all : pre_make $(OUT)
else
all : $(OUT)
endif

$(OUT) : $(OBJS)
ifeq ($(suffix $(OUT)),.a)
	ar -rc $(OUT) $(patsubst %.o,./objs/%.o,$(OBJS))
else
ifeq ($(suffix $(OUT)),.so)
	$(LD) -shared -fPIC $(ARG_m32) $(patsubst %.o,./$(DIR_OBJS)/%.o,$(OBJS)) $(LDFLAGS) -o $(OUT)
else
	$(LD) $(ARG_m32) $(patsubst %.o,./$(DIR_OBJS)/%.o,$(OBJS)) $(LDFLAGS) -o $(OUT)
endif
endif

%.o : %.cpp
	[ -d $(DIR_OBJS) ] || mkdir -p $(DIR_OBJS)
	$(CXX) $(CXXFLAGS) $(INCLUDES) -c $< -o ./$(DIR_OBJS)/$@

%.o : %.c
	[ -d $(DIR_OBJS) ] || mkdir -p $(DIR_OBJS)
	$(CC) $(CFLAGS) $(INCLUDES) -c $< -o ./$(DIR_OBJS)/$@

$(DIR_DEPS)/%.d : %.cpp
	[ -d $(DIR_DEPS) ] || mkdir -p $(DIR_DEPS)
	$(CXX) $(INCLUDES) -MM -MD $< -o $@

$(DIR_DEPS)/%.d : %.c
	[ -d $(DIR_DEPS) ] || mkdir -p $(DIR_DEPS)
	$(CC) $(INCLUDES) -MM -MD $< -o $@

-include $(addprefix $(DIR_DEPS)/,$(DEPS))

pre_make:
	@for d in $(PRE_MAKE_DIRS); do \
	  if test -d "$$d"; then \
	    cd $$d && $(MAKE) $(MAKECMDGOALS); \
		cd $(PWD); \
	  fi; \
	done;

ifdef PRE_MAKE_DIRS
clean : pre_make
else
clean :
endif
	rm -rf objs $(OUT)
	@echo all cleaned

rebuild : clean all

.PHONY : all clean rebuild
